#include "stm32f4xx_hal.h"
#include "iic.h"
#include "mlx90614.h"
#include "printf.h"
#include "delay.h"

uint16_t smbus_readmemory(uint8_t slaveAddress, uint8_t command)
{
	float data;			// Data storage (DataH:DataL)
	uint8_t Pec;				// PEC byte storage
	uint8_t DataL = 0;			// Low data byte storage
	uint8_t DataH = 0;			// High data byte storage
	uint8_t arr[6];			// Buffer for the sent bytes
	uint8_t PecReg;			// Calculated PEC byte storage

	iic2_start();
	iic2_send_single_byte(slaveAddress);		//发送器件地址和写方向位
	iic2_wait_ack();
	iic2_send_single_byte(command);				//发送器件地址和写方向位
	iic2_wait_ack();

	iic2_start();
	iic2_send_single_byte(slaveAddress + 1);		//发送器件地址和写方向位
	iic2_wait_ack();

	DataL = iic2_recv_single_byte(1);		//每次读取完毕，发送值为0(停止)或1(继续接收)的ACK信号
	DataH = iic2_recv_single_byte(1);		//每次读取完毕，发送值为0(停止)或1(继续接收)的ACK信号
	Pec = iic2_recv_single_byte(0);		//每次读取完毕，发送值为0(停止)或1(继续接收)的ACK信号
	iic2_stop();
	arr[5] = slaveAddress;		//
	arr[4] = command;			//
	arr[3] = slaveAddress + 1;	//Load array arr
	arr[2] = DataL;				//
	arr[1] = DataH;				//
	arr[0] = 0;					//

	PecReg = PEC_Calculation(arr);				//Calculate CRC
	data = ((uint16_t) DataH << 8) | DataL;	//data=DataH:DataL
	data = data * 0.02 - 273.15;
	debug_printf("temp:%f\r\n", data);
	return 0;
}

uint8_t PEC_Calculation(uint8_t *pec)
{
	uint8_t crc[6];	//
	uint8_t BitPosition = 47;	//
	uint8_t shift;
	uint8_t i;
	uint8_t j;
	uint8_t temp;

	do {
		/*Load pattern value 0x00 00 00 00 01 07*/
		crc[5] = 0;
		crc[4] = 0;
		crc[3] = 0;
		crc[2] = 0;
		crc[1] = 0x01;
		crc[0] = 0x07;

		/*Set maximum bit position at 47 ( six bytes byte5...byte0,MSbit=47)*/
		BitPosition = 47;

		/*Set shift position at 0*/
		shift = 0;

		/*Find first "1" in the transmited message beginning from the MSByte byte5*/
		i = 5;
		j = 0;
		while ((pec[i] & (0x80 >> j)) == 0 && i > 0) {
			BitPosition--;
			if (j < 7) {
				j++;
			} else {
				j = 0x00;
				i--;
			}
		}/*End of while */

		/*Get shift value for pattern value*/
		shift = BitPosition - 8;

		/*Shift pattern value */
		while (shift) {
			for (i = 5; i < 0xFF; i--) {
				if ((crc[i - 1] & 0x80) && (i > 0)) {
					temp = 1;
				} else {
					temp = 0;
				}
				crc[i] <<= 1;
				crc[i] += temp;
			}/*End of for*/
			shift--;
		}/*End of while*/

		/*Exclusive OR between pec and crc*/
		for (i = 0; i <= 5; i++) {
			pec[i] ^= crc[i];
		}/*End of for*/
	} while (BitPosition > 8); /*End of do-while*/
	return pec[0];
}
